<template>
  <div style="height: 100%;">
    <crud-table ref="crudTableRef" :config="articleConfig" />
  </div>
</template>

<script setup>
import { h, ref, onMounted } from 'vue'
import { NTag, NSwitch, useMessage } from 'naive-ui'
import moment from 'moment'
import CrudTable from '@/components/CrudTable/index.vue'
import WangEditor from '@/components/WangEditor/index.vue'
import request from '@/utils/request.js'

const message = useMessage()
const crudTableRef = ref(null)

// 添加文章类型选项
const articleTypes = ref([])

// 获取文章类型字典
const fetchArticleTypes = async () => {
    const res = await request.get('/dictionary-details/article_type')
    articleTypes.value = res.map(item => ({
      label: item.dict_value,
      value: item.dict_key
    }))
}

// 在组件挂载时获取文章类型
onMounted(() => {
    fetchArticleTypes()
})

const articleConfig = ref({
  title: '文章管理',
  apiPrefix: '/articles',
  primaryKey: 'id',
  // 启用搜索
  searchable: false,
  searchFields: [
    {
      label: '类型',
      key: 'type',
      type: 'select', // 改为下拉选择
      options: articleTypes, // 使用字典数据
      placeholder: '请选择文章类型'
    }
  ],

  // 启用基础操作
  creatable: true,
  editable: true,
  deletable: true,
  switchable:true,
  switchKey:'status',
  // 表格配置
  tableConfig: {
    pagination: true,
    bordered: false,
    size: 'medium',
    scrollX: 1200
  },

  // 表格列配置
  columns: [
    {
      title: '类型',
      key: 'type',
      ellipsis: true,
      render: (row) => {
        const type = articleTypes.value.find(t => t.value === row.type)
        return type ? type.label : row.type
      }
    },
    {
      title: '创建时间',
      key: 'created_at',
      render: (row) => {
        return row.created_at && moment(row.created_at).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      title: '更新时间',
      key: 'updated_at',
      render: (row) => {
        return row.updated_at && moment(row.updated_at).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  ],

  // 添加表单弹窗配置
  formConfig: {
    width: '1000px', // 设置弹窗宽度
    labelWidth: 100,
    labelPlacement: 'left',
    requireMarkPlacement: 'right-hanging'
  },

  // 表单配置
  formFields: [
    {
      label: '类型',
      key: 'type',
      type: 'select', // 改为下拉选择
      options: articleTypes, // 使用字典数据
      span: 24,
      rules: [{ required: true, message: '请选择文章类型' }]
    },
    {
      label: '内容',
      key: 'content',
      type: 'custom',
      span: 24,
      rules: [{ required: true, message: '请输入文章内容' }],
      render: ({ value, onChange }) => {
        return h(WangEditor, {
          value,
          'onUpdate:value': onChange,
          height: 600 // 增加编辑器高度
        })
      }
    },
  ],

  // 表单验证规则
  rules: {
    type: { required: true, message: '请输入文章类型' },
    content: { required: true, message: '请输入文章内容' }
  }
})
</script>

<style lang="scss" scoped>
.n-switch {
  vertical-align: middle;
}

:deep(.wang-editor) {
  margin-bottom: 24px;
  min-height: 650px; // 设置最小高度

  .editor-content {
    width: 100%;
  }
}
</style>
